package chuangyi.com.org.ViewModel;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.databinding.Bindable;
import android.databinding.tool.util.L;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.LayerDrawable;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTimestamp;
import android.media.AudioTrack;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.databinding.library.baseAdapters.BR;
import com.solidfire.gson.internal.LinkedTreeMap;

import java.io.File;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;

import chuangyi.com.org.DOMIHome.Fragments.CommonFragment;
import chuangyi.com.org.DOMIHome.Fragments.HomeFragment;
import chuangyi.com.org.DOMIHome.HomeActivity;
import chuangyi.com.org.DOMIHome.PopupActivity;
import chuangyi.com.org.DOMIHome.R;
import chuangyi.com.org.DOMIHome.SaveContent;
import chuangyi.com.org.DOMIHome.Utils.AudioRecoderUtils;
import chuangyi.com.org.DOMIHome.Utils.HttpUtil;
import chuangyi.com.org.DOMIHome.Utils.OSSUtil;
import chuangyi.com.org.DOMIHome.Utils.Utils;
import chuangyi.com.org.DOMIHome.Utils.WebApi;
import chuangyi.com.org.DOMIHome.WaitActivityResult;
import chuangyi.com.org.DOMIHome.WxPayInfoModel;
import chuangyi.com.org.DOMIHome.adapter.ListBindingAdapter;

/**
 * Created by zxh on 16/12/8.
 */

public class AdviceInfo extends ObservableWithGoBackHandler implements WaitActivityResult,
        AudioRecoderUtils.OnAudioStatusUpdateListener, SaveContent {
    public static final int VOICE_TYPE = 1, TEXT_TYPE = 0;
    private boolean allowSend;
    private boolean allowReply;
    private boolean paid;
    private boolean voice;
    private boolean expert;
    private boolean allowComment;
    private double charge;
    private int expertId;
    private int time;
    private int type;
    private String avatar;
    private String realName;
    private String company;
    private String job;
    private String nickName;
    private String content;
    private AudioRecoderUtils recorder;
    private MediaPlayer player;
    //    private String timeline;
    private Integer adviceId;
    private boolean loading;
    private ListBindingAdapter adviceContentList;

    @Bindable
    public String getJob() {
        return job;
    }

    public void setJob(String job) {
        this.job = job;
    }

    @Bindable
    public String getNickName() {
        return nickName;
    }

    public void setNickName(String nickName) {
        this.nickName = nickName;
        notifyPropertyChanged(BR.nickName);
    }

    @Bindable
    public String getRealName() {
        return realName;
    }

    public void setRealName(String realName) {
        this.realName = realName;
        super.getHandler().setTitle(realName);
        notifyPropertyChanged(BR.realName);
    }

    @Bindable
    public String getAvatar() {
        return avatar;
    }

    public void setAvatar(String avatar) {
        this.avatar = avatar;
    }

    @Bindable
    public String getCompany() {
        return company;
    }

    public void setCompany(String company) {
        this.company = company;
    }

    @Bindable
    public boolean isAllowSend() {
        return allowSend;
    }

    public void setAllowSend(boolean allowSend) {
        this.allowSend = allowSend;
        notifyPropertyChanged(BR.allowSend);
    }

    @Bindable
    public boolean isAllowReply() {
        return allowReply;
    }

    public void setAllowReply(boolean allowReply) {
        this.allowReply = allowReply;
        notifyPropertyChanged(BR.allowReply);
    }

    @Bindable
    public boolean isAllowComment() {
        return allowComment;
    }

    public void setAllowComment(boolean allowComment) {
        this.allowComment = allowComment;
        notifyPropertyChanged(BR.allowComment);
    }

    @Bindable
    public ListBindingAdapter getAdviceContentList() {
        return adviceContentList;
    }

    @Bindable
    public boolean isPaid() {
        return paid;
    }

    void setPaid(boolean paid) {
        this.paid = paid;
        if (this.paid) {
            setAllowComment(true);
        } else {
            setAllowComment(false);
        }
        notifyPropertyChanged(BR.paid);
    }

    @Bindable
    public boolean isVoice() {
        return voice;
    }

    public void setVoice(boolean voice) {
        this.voice = voice;
        notifyPropertyChanged(BR.voice);
    }

    @Bindable
    public double getCharge() {
        return charge;
    }

    public int getExpertId() {
        return expertId;
    }

    public void setExpertId(int expertId) {
        this.expertId = expertId;
    }

    @Bindable
    public boolean isExpert() {
        return expert;
    }

    public void setExpert(boolean expert) {
        this.expert = expert;
        if (expert) {
            setVoice(true);
            setAllowReply(true);
        } else {
            setAllowReply(false);
        }
        notifyPropertyChanged(BR.expert);
    }

    public Integer getAdviceId() {
        return adviceId;
    }

    public void setAdviceId(Integer adviceId) {
        if (adviceId != null) {
            setAllowSend(false);
            load();
        } else {
            setAllowSend(true);
        }
        this.adviceId = adviceId;
    }

    public AdviceInfo(Context context, String userName, String company, boolean isExpert) {
        super(context);
        super.getHandler().setSecondTitle(company);
        setRealName(userName);
        setExpert(isExpert);
        List<Integer> layoutTypes = new ArrayList<Integer>();
        layoutTypes.add(R.layout.i_advice_mine_text);
        layoutTypes.add(R.layout.i_advice_their_text);
        layoutTypes.add(R.layout.i_advice_mine_voice);
        layoutTypes.add(R.layout.i_advice_their_voice);

        adviceContentList = new ListBindingAdapter(context, BR.advice, layoutTypes);
        allowSend = true;
        time = 0;
    }

    @Bindable
    public String getTimeline() {
        NumberFormat numberFormat = NumberFormat.getNumberInstance();
        numberFormat.setMinimumIntegerDigits(2);
        return numberFormat.format(time / 60) + ":" + numberFormat.format(time % 60);
    }

    public int getType() {
        return type;
    }

    @Bindable
    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
        notifyPropertyChanged(BR.content);
    }

    public void load() {
        if (loading) {
            return;
        }
        loading = true;
        new Thread(new Runnable() {
            @Override
            public void run() {
                LinkedTreeMap result = WebApi.adviceDetail(getContext(), getAdviceId());
                try {
                    setPaid(Utils.getBooleanValue(result.get("payflag")));

                    setAllowComment(Utils.getBooleanValue(result.get("status")));

                    ArrayList list = (ArrayList) result.get("list");

                    for (Object answer : list) {
                        LinkedTreeMap map = (LinkedTreeMap) answer;
                        AdviceItem item = new AdviceItem(getContext());
                        item.setReaded(Utils.getBooleanValue(result.get("flag")));
                        if (expert) {
//                            item.setUid(Utils.getIntValue(map.get("uid")));
                            setPaid(false);
                            item.setUid(0);
                        } else {
                            item.setUid(User.getCurrentUser().getUid());
                        }
                        item.setType(Utils.getIntValue(map.get("contenttype")));
                        item.setContent((String) map.get("question"));
                        item.setAvatar((String) map.get("avatar"));
                        item.setJob((String) map.get("job"));
                        item.setNickName((String) map.get("nickname"));

                        setNickName(item.getNickName());
                        setAvatar(item.getAvatar());
                        setJob(item.getJob());

                        charge = Utils.getDoubleValue(map.get("charge"));
                        item.setUploadDate(Utils.getDateFromFormat(map.get("sysdate"), "yyyy-MM-dd HH:mm:ss"));
                        item.setParent(AdviceInfo.this);
                        adviceContentList.add(item);
                        if (item.getType() == AdviceInfo.VOICE_TYPE) {
                            setNickName(item.getNickName());
                            setAvatar(item.getAvatar());
                            setJob(item.getJob());
                        }

                        ArrayList replyList = (ArrayList) map.get("users");
                        if (replyList == null) {
                            return;
                        } else {
                            for (Object reply : replyList) {
                                LinkedTreeMap replyMap = (LinkedTreeMap) reply;
                                item = new AdviceItem(getContext());
                                item.setParent(AdviceInfo.this);
                                item.setUid(Utils.getIntValue(replyMap.get("uid")));
                                item.setContent((String) replyMap.get("content"));
                                item.setType(Utils.getIntValue(replyMap.get("contenttype")));
                                item.setReaded(Utils.getBooleanValue(replyMap.get("flag")));
                                item.setUploadDate(Utils.getDateFromTimestamp(replyMap.get("systime")));
                                item.setTimes((String) replyMap.get("times"));
                                adviceContentList.add(item);
                            }
                        }
                    }
                    // 设置界面状态
                    if (expert) {
                        setVoice(true);
                        setAllowSend(false);
                        setAllowReply(true);
                    } else {
                        setVoice(false);
                        setAllowSend(false);
                        setAllowReply(false);
                        setAllowComment(paid);
                    }
                    notifyDataSetChanged(adviceContentList);
                } catch (Exception ex) {
                    showToast("解析数据时发生错误");
                }
                notifyDataSetChanged(adviceContentList);
            }
        }).start();
    }

    /**
     * 点击去评论
     *
     * @param view
     */
    public void onClickComment(View view) {
        Activity activity = (Activity) getContext();
        ExpertCommentModel model = new ExpertCommentModel(activity, expertId);
        model.setAvatar(getAvatar());
        model.setJob(getJob());
        model.setConsultId(getAdviceId());
        model.setNickName(getNickName());
        model.setRealName(getRealName());
//        model.setRealName();
        model.setCompany(getCompany());
        CommonFragment fragment = new CommonFragment();

        fragment.setInitCallback(new CommonFragment.Callback() {
            @Override
            public void viewCreated(View root) {
                RatingBar ratingBar = (RatingBar) root.findViewById(R.id.ratingBar);
                LayerDrawable drawable = (LayerDrawable) ratingBar.getProgressDrawable();
                drawable.getDrawable(2).setColorFilter(Color.argb(0xff, 0xff, 0xb4, 0x34), PorterDuff.Mode.SRC_ATOP);
            }
        });
        fragment.setDataModel(model);
        fragment.setLayoutId(R.layout.f_expert_comment);
        fragment.setVariableId(BR.complain);
        HomeActivity.switchFragment(activity, fragment);
    }

    public void onClickSend(View view) {
        if (expert) {
            return;
        } else {
            if ("".equals(content) || content == null) {
                Toast.makeText(getContext(), "请输入咨询内容", Toast.LENGTH_SHORT).show();
            } else {
                Activity activity = (Activity) getContext();
                PopupActivity.startActivityForResult(activity, R.layout.v_dialog_advice_confirm,
                        HomeActivity.REQUEST_DIALOGTIP, BR.model, new DialogModel(activity));
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {

            if (requestCode == HomeActivity.REQUEST_DIALOGTIP) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        send(TEXT_TYPE, content, "");
                    }
                }).start();
            } else if (requestCode == HomeActivity.REQUEST_PAY) {
                DialogModel model = new DialogModel(getContext());
                PopupActivity.startActivity((Activity) getContext(), R.layout.v_dialog_advice_pay_success,
                        BR.dialog, model);
            }
        }
    }

    /**
     * 开始录音
     */
    public void startRecord() {
        time = 0;
        notifyPropertyChanged(BR.timeline);
        recorder = new AudioRecoderUtils();
        recorder.setOnAudioStatusUpdateListener(this);
        recorder.startRecord();
    }

    /**
     * 结束录音
     */
    public void stopRecord() {
        recorder.stopRecord();
        recorder = null;
    }

    public void cancelRecord() {
        time = 0;
        notifyPropertyChanged(BR.timeline);
        recorder.cancelRecord();
        recorder = null;
    }

    public void send(int type, String content, String times) {
        this.type = type;
        if (expert) {
            // 回复
            final AdviceItem advice = new AdviceItem(getContext());
            advice.setContent(content);
            advice.setType(type);

            if (WebApi.sendAnswer(getContext(), advice, adviceId, times)) {
                advice.setUid(User.getCurrentUser().getUid());
                advice.setParent(this);
                advice.setTimes(times);
                advice.setUploadDate(Calendar.getInstance().getTime());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adviceContentList.add(advice);
                        adviceContentList.notifyDataSetChanged();
                    }
                });
            }
        } else {
            // 咨询
            if (WebApi.sendAdvice(getContext(), this, content)) {
                ((Activity) getContext()).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        ObservableWithGoBackHandler handler = new ObservableWithGoBackHandler(getContext());
                        handler.getHandler().setTitle(getHandler().getTitle());
                        handler.getHandler().setSecondTitle(getHandler().getSecondTitle());
                        CommonFragment fragment = new CommonFragment();
                        fragment.setLayoutId(R.layout.f_advice_commit);
                        fragment.setVariableId(BR.handler);
                        fragment.setDataModel(handler);
                        HomeActivity.popFragment();
                        HomeActivity.switchFragment((Activity) getContext(), fragment);
                    }
                });
            }
        }
    }

    @Override
    public void onUpdate(double db, long time) {
        this.time = (int) (time / 1000);
        notifyPropertyChanged(BR.timeline);
    }

    @Override
    public void onStop(String filePath) {
        if (time <= 0) {
            showToast("时间过短");
            time = 0;
            notifyPropertyChanged(BR.timeline);
            return;
        }
        final String path = filePath;
        try {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    String url = OSSUtil.uploadFile(getContext().getApplicationContext(), path);
                    send(VOICE_TYPE, url, getTimeline());
                    time = 0;
                    notifyPropertyChanged(BR.timeline);
                }
            }).start();
        } catch (Exception ex) {

        }
    }

    @Override
    public boolean check() {
        return true;
    }

    @Override
    public void save() {
        if (player != null) {
            player.stop();
            player.release();
            player = null;
        }
        HomeActivity.cancelFragment();
    }

    /**
     * 显示付款界面
     */
    public void showPayActivity() {
        final Activity activity = (Activity) getContext();
        PayModel model = new PayModel(getContext(), charge);
        model.setTitle("听取专家全部回答");
        model.setPayCallback(new PayModel.Callback() {
            @Override
            public boolean onPay(final PayItem payType) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String type = payType.getType() == PayModel.PAY_ALI ? "ali" : "wx";
                        String result = WebApi.payCharge(getContext(), getAdviceId(), type);
                        if (result == null)
                            return;
                        if (payType.getType() == PayModel.PAY_ALI) {
                            LinkedTreeMap map = HttpUtil.fromJson(result, LinkedTreeMap.class);
                            result = (String) map.get("orderinfo");
                            payType.setPayData(result);
                        } else {
                            LinkedTreeMap map = HttpUtil.fromJson(result, LinkedTreeMap.class);
                            map = (LinkedTreeMap) map.get("orderinfo");
                            WxPayInfoModel model = new WxPayInfoModel();
                            model.setAppid((String) map.get("appid"));
                            model.setPartnerid((String) map.get("partnerid"));
                            model.setPrepayid((String) map.get("prepayid"));
                            model.setTimestamp((String) map.get("timestamp"));
                            model.setNoncestr((String) map.get("noncestr"));
                            model.setPackage((String) map.get("package"));
                            model.setSign((String) map.get("sign"));

                            payType.setPayData(model);
                        }
                        payType.getParent().callPay(payType);
                    }
                }).start();
                return false;
            }
        });

//        model.setResultCallback(new PayModel.ResultCallback() {
//            @Override
//            public void onSuccess() {
//                DialogModel model = new DialogModel(getContext());
//                PopupActivity.startActivity(activity, R.layout.v_dialog_advice_pay_success, BR.model, model);
//            }
//
//            @Override
//            public void onCancel() {
//
//            }
//
//            @Override
//            public void onError() {
//
//            }
//        });
        PopupActivity.startActivityForResult(activity, R.layout.v_dialog_advice_pay,
                HomeActivity.REQUEST_PAY, BR.payModel, model);
    }

    public boolean allowPlay() {
        return WebApi.allowPlay(getContext(), adviceId);
    }


    public void playSound(final String url) {
        if (player != null) {
            player.stop();
            player.release();
            player = null;
        }
        Uri uri = Uri.parse(url);
        player = MediaPlayer.create(getContext(), uri);
        player.start();
    }

    public static void openAdvice(final AdviceInfo adviceInfo) {
        final CommonFragment fragment = new CommonFragment();
        fragment.setInitCallback(new CommonFragment.Callback() {
            @Override
            public void viewCreated(View root) {
                final Button sendBtn = (Button) root.findViewById(R.id.send_btn);
                final ImageView imageView = (ImageView) root.findViewById(R.id.inputVoice);
                final TextView textView = (TextView) root.findViewById(R.id.tips);
                imageView.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View view, MotionEvent motionEvent) {
                        int action = motionEvent.getAction();
                        if (action == MotionEvent.ACTION_DOWN) {
                            imageView.setImageResource(R.mipmap.inptvoic_act);
                            adviceInfo.startRecord();
                            textView.setText("松开发送");
                            // 处理开始录音
                        } else if (action == MotionEvent.ACTION_UP) {
                            imageView.setImageResource(R.mipmap.inptvoic);
                            textView.setText("按住录音");
                            if (Utils.isContain(imageView, motionEvent.getRawX(), motionEvent.getRawY())) {
                                adviceInfo.stopRecord();
                            } else {
                                adviceInfo.cancelRecord();
                            }
                            // 处理发送语音
                        } else if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_OUTSIDE) {
                            // 处理取消
                            imageView.setImageResource(R.mipmap.inptvoic);
                            adviceInfo.cancelRecord();
                            textView.setText("按住录音");
                        }
                        return false;
                    }
                });
                EditText inputContent = (EditText) root.findViewById(R.id.advice_content);
                inputContent.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                    @Override
                    public void onFocusChange(View view, boolean b) {
                        CommonFragment fragment1 = new CommonFragment();
                        fragment1.setDataModel(adviceInfo);
                        fragment1.setVariableId(BR.adviceInfo);
                        fragment1.setLayoutId(R.layout.f_send_advice);
                        fragment1.setInitCallback(new CommonFragment.Callback() {
                            @Override
                            public void viewCreated(View root) {
                                EditText text = (EditText) root.findViewById(R.id.advice_content);
                                text.requestFocus();
                            }
                        });
                        HomeActivity.popFragment();
                        HomeActivity.switchFragment((Activity) adviceInfo.getContext(), fragment1);
                    }
                });
            }
        });
        fragment.setLayoutId(R.layout.f_advice);
        fragment.setDataModel(adviceInfo);
        fragment.setVariableId(chuangyi.com.org.DOMIHome.BR.adviceInfo);
        HomeActivity.switchFragment((Activity) adviceInfo.getContext(), fragment);
    }
}
